package com.web.boot.web.wechat;

import com.blue.core.dict.HttpMethod;
import com.blue.core.dict.annotation.DictParser;
import com.blue.http.annotation.Http;
import com.blue.http.message.HttpRequest;
import com.blue.http.message.View;
import com.blue.validation.ValidationUtil;
import com.blue.validation.group.SaveModel;
import com.blue.validation.group.UpdateModel;
import com.web.base.wechat.facade.WechatFacade;
import com.web.base.wechat.message.WechatRequest;
import com.web.base.wechat.message.WechatResponse;
import com.web.core.async.redis.CacheRefreshSender;
import com.web.core.util.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
@Http(url = "/wechat")
public class WechatController
{
	@Autowired
	private WechatFacade wechatFacade;
	@Autowired
	private CacheRefreshSender cacheRefreshSender;
	
	private DictParser dictParser = DictParser.getInstance();
	
	public WechatController()
	{
	}
	
	@Http(url = "/wechat_list", method = HttpMethod.GET)
	public View listGet(HttpRequest request)
	{
		WechatRequest wechatRequest = request.getQueryObject(WechatRequest.class);
		return View.createBuilder().setView("/wechat/wechat_list")
				.put("map", dictParser.getStringMap())
				.put("model", wechatRequest)
				.put("page", wechatFacade.listPage(wechatRequest, Const.PAGE_START, Const.PAGE_SIZE))
				.build();
	}
	
	@Http(url = "/wechat_list", method = HttpMethod.POST)
	public View listPost(HttpRequest request)
	{
		WechatRequest wechatRequest = request.getPostObject(WechatRequest.class);
		int start = request.getPostInt("start", Const.PAGE_START);
		return View.createBuilder().setView("/wechat/wechat_list_grid")
				.put("page", wechatFacade.listPage(wechatRequest, start, Const.PAGE_SIZE))
				.build();
	}
	
	@Http(url = "/wechat_get", method = HttpMethod.GET)
	public View get(HttpRequest request)
	{
		int id = request.getQueryInt("id", 0);
		WechatResponse response = null;
		if (id > 0)
		{
			response = wechatFacade.get(id);
		}
		return View.createBuilder().setView("/wechat/wechat_get")
				.put("model", response == null ? new WechatResponse() : response)
				.put("map", dictParser.getStringMap())
				.build();
	}
	
	@Http(url = "/wechat_save", method = HttpMethod.POST)
	public void save(HttpRequest request)
	{
		WechatRequest wechatRequest = request.getPostObject(WechatRequest.class);
		WechatResponse response = null;
		if (wechatRequest.getId() == null)
		{
			ValidationUtil.valid(wechatRequest, SaveModel.class);
			response = wechatFacade.add(wechatRequest);
		}
		else
		{
			ValidationUtil.valid(wechatRequest, UpdateModel.class);
			response = wechatFacade.update(wechatRequest);
		}
	}
	
	@Http(url = "/wechat_refresh", method = HttpMethod.POST)
	public void refresh(HttpRequest request)
	{
		cacheRefreshSender.send(CacheRefreshSender.WECHAT_CACHE);
	}
	
}
